package com.zhk.entry.observer;


import com.zhk.entry.proxy.StuInvocationHandler;
import com.zhk.entry.util.IThreadConn;

import java.lang.reflect.Proxy;
import java.sql.SQLException;
import java.util.Observable;
import java.util.Observer;

/**
 * 观察者
 *
 * @param <T>
 */
public class BaseObserver<T> implements Observer {
    private String name;

    private Observable observable;

    private IThreadConn iThreadConn;

    private T target;

    public void setObserver(String name, Observable observable, IThreadConn iThreadConn, T target) {
        this.name = name;
        this.target = target;
        this.observable = observable;
        this.iThreadConn = iThreadConn;
        this.observable.addObserver((Observer) Proxy.newProxyInstance(BaseObserver.class.getClassLoader(), BaseObserver.class.getInterfaces(), new StuInvocationHandler(target)));
    }

    @Override
    public void update(Observable o, Object arg) {
        String msg = (String) arg;

        if ("commit".equals(msg)) {
            try {
                System.out.println("观察者："+name + "：事务提交");
                iThreadConn.commitTransaction();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if ("rollback".equals(msg)) {
            try {
                System.out.println("观察者："+name + "：事务回滚");
                iThreadConn.rollbackTransaction();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
